<template>
  <div class="app-container documentation-container">
    <div style="margin-bottom: 20px;">
      <DataPresentation
        :list="statisticsList"
        :loading="statisticsDataLoading"
      />
    </div>

    <el-card style="margin-bottom: 20px;border: none;" shadow="never" class="search">
      <SearchCondition v-model="searchCondition" @search="onSubmit">
        <template v-slot:extra>
          <el-form-item label="姓名">
            <el-input v-model="form.username" placeholder="请输入姓名" clearable />
          </el-form-item>

          <el-form-item label="部门">
            <el-cascader
              ref="deptCascader"
              v-model="form.department_id"
              :options="dept"
              placeholder="选择部门"
              size="medium"
              clearable
              :props="{
                value: 'id',
                label: 'name',
                checkStrictly: true
              }"
            />
          </el-form-item>
          <el-form-item label="职位">
            <el-select
              v-model="form.position_id"
              multiple
              size="medium"
              placeholder="请选择"
              @change="(data) => selectCompanyChange(data, 'position')"
            >
              <el-option
                v-for="item in position"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="form.job_status"
              size="medium"
              multiple
              placeholder="请选择"
              @change="(data) => selectCompanyChange(data, 'job_status')"
            >
              <el-option
                v-for="item in condition"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否转正">
            <el-select
              v-model="form.identity"
              size="medium"
              placeholder="请选择"
              clearable
            >
              <el-option
                label="已转正"
                :value="0"
              />
              <el-option
                label="待转正"
                :value="1"
              />
            </el-select>
          </el-form-item>
        </template>
      </SearchCondition>

    </el-card>

    <el-card shadow="never" style="border: none; padding-bottom: 20px;">
      <div class="employee__header">
        <el-button
          type="primary"
          :disabled="currentEmployees.length <= 0"
          @click="handleExportEmployeesInfo"
        >导出员工信息</el-button>
      </div>
      <el-table
        ref="elTableRef"
        v-loading="loading"
        :data="tableData"
        :row-key="getRowKey"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column align="header-center" label="性别">
          <template slot-scope="scope">
            <span v-if="scope.row.gender == 1">男</span>
            <span v-else-if="scope.row.gender == 0">女</span>
            <span v-else>不详</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="register_at"
          label="入职日期"
        >
          <template v-slot="{ row }">
            {{ row.entry_at ? dayjs(row.entry_at).format('YYYY-MM-DD') : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="education_id" label="学历">
          <template v-slot="{ row }">
            {{ row.education_id?.valueType?.name }}
          </template>
        </el-table-column>
        <el-table-column label="年龄">
          <template v-slot="{ row }">
            {{ getAge(row?.birthday_at) }}
          </template>
        </el-table-column>
        <el-table-column label="部门">
          <template v-slot="{ row }">
            {{
              row.department_id?.valueType?.delete === 0 ?
                row.department_id?.valueType?.name : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column label="职位">
          <template v-slot="{ row }">
            {{
              row.position_id?.valueType?.delete === 0 ?
                row.position_id?.valueType?.name : '-'
            }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlerShow(scope.row)">
              <i class="el-icon-view" /> 查看
            </el-button>
            <el-dropdown
              trigger="click"
              @command="(data) => handleCommand(data, scope.row)"
            >
              <el-button type="text" size="small" style="margin-left: 10px;">
                <i class="el-icon-more" /> 更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">修改密码</el-dropdown-item>
                <el-dropdown-item command="3">
                  {{ scope.row.job_status / 1 === 1 ? '设置离职' : '设置在职' }}
                </el-dropdown-item>
                <!--                <el-dropdown-item command="2">修改宿舍</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-if="meta.total"
        style="margin-top: 0; padding-bottom: 0;"
        :total="meta.total"
        :limit="meta.per_page"
        @pagination="pagination"
      />
    </el-card>
    <el-dialog
      title="宿舍选择"
      :visible.sync="dormitoryCheckDialogVisible"
      :close-on-click-modal="false"
      width="40%"
    >
      <Dorm ref="dorm" :user-id="num.toString()" @closeMain="dormitoryChange" />
    </el-dialog>
    <PassWordEdit
      v-if="pwdDialogVisible"
      :id="pwdId"
      :dialog-visible.sync="pwdDialogVisible"
      @finish="pwdFinish"
    />

    <ResignationDialog
      :visible.sync="resignationDialogVisible"
      :user-id="resignationUser"
      :btn-loading="resignationDialogBtnLoading"
      @confirm="handleResignationDialogConfirm"
    />
  </div>
</template>

<script>
import SearchCondition from './components/SearchCondition/index.vue'
import Pagination from '@/components/Pagination'
import PassWordEdit from '@/components/PassWord/Edit'
import DataPresentation from '@/views/personnel-files/components/DataPresentation/DataPresentation.vue'
import { getAllUser, dataStatistics, exportEmployeeInfo, administratorModifyFile } from '@/api/v2/personnel'
import { deepClone } from '@/utils'
import { getDept, getPosition } from '@/api/basic'
import Dorm from '@/components/Check/Dorm'
import { isObjectEqual } from '@/utils/kris_utils'
import dayjs from 'dayjs'
import StatisticsCard from '@/components/StatisticsCard/StatisticsCard.vue'
import ResignationDialog from '@/views/personnel-files/components/ResignationDialog/ResignationDialog.vue'
export default {
  name: 'PersonnelFiles',
  components: {
    StatisticsCard,
    Pagination,
    PassWordEdit,
    Dorm,
    SearchCondition,
    DataPresentation,
    ResignationDialog
  },
  data() {
    return {
      dormitoryCheckDialogVisible: false,
      dormitory: {
        user_id: '',
        room_id: ''
      },
      num: '',
      form: {
        job_status: [1],
        identity: null,
        username: ''
      },
      tableData: [],
      dept: [],
      position: [],
      loading: false,
      postData: {},
      searchCondition: {},
      pageData: {
        paginate: 10,
        page: 1
      },
      condition: [
        {
          name: '在职',
          id: 1
        },
        {
          name: '离职',
          id: 0
        }
      ],
      meta: {},
      pwdDialogVisible: false,
      pwdId: null,
      statisticsData: {},
      currentEmployees: [],
      statisticsDataLoading: false,
      resignationDialogVisible: false,
      resignationUser: null,
      resignationDialogBtnLoading: false
    }
  },
  computed: {
    statisticsList() {
      const { birthdayCount, man, woman, userCount, user, birthday, employeeCount } = this.statisticsData
      return [
        {
          label: '全体员工',
          value: employeeCount,
          icon: 'all-employee'
        },
        {
          label: '男性数量',
          value: man,
          icon: 'man-count-new'
        },
        {
          label: '女性数量',
          value: woman,
          icon: 'woman-count-new'
        },
        {
          label: '本月生日',
          value: birthdayCount,
          month: birthday,
          icon: 'birthday-new'
        },
        {
          label: '合同到期',
          value: userCount,
          additional: user,
          icon: 'expiration-of-contract-new'
        }
      ]
    }
  },
  created() {
    this.searchEvent()
    // Mock: get all routes and roles list from server
    this.init()
  },
  methods: {
    dayjs,

    init() {
      Promise.allSettled([
        this.onSubmit(),
        // this.getUsers(),
        this.getDepts(),
        this.getPositions(),
        this.getDataStatistics()
      ])
    },

    searchEvent() {
      const { job_status, identity } = this.$route.query
      if (job_status || job_status === 0) {
        this.form.job_status.push(job_status / 1)
        this.onSubmit()
      } else if (identity || identity === 0) {
        this.form.identity = identity / 1
        this.onSubmit()
      }
    },

    async getDataStatistics() {
      this.statisticsDataLoading = true
      try {
        const res = await dataStatistics()
        this.statisticsData = res.data
      } catch (error) {
        console.log('error ------>', error)
      } finally {
        this.statisticsDataLoading = false
      }
    },

    getAge(val) {
      if (val) {
        const currentYear = new Date().getFullYear() // 当前的年份
        const calculationYear = new Date(val).getFullYear() // 计算的年份
        const wholeTime = currentYear + val.substring(4) // 周岁时间
        const calculationAge = currentYear - calculationYear // 按照年份计算的年龄
        // 判断是否过了生日
        if (new Date().getTime() > new Date(wholeTime).getTime()) {
          return calculationAge
        } else {
          return calculationAge - 1
        }
      }
    },
    dormitoryChange(data) {
      this.getUsers()
      this.getDepts()
      this.getPositions()
      this.dormitoryCheckDialogVisible = false
    },
    selectCompanyChange() {
      console.log(this.form)
    },
    async getDepts() {
      const res = await getDept()

      if (isObjectEqual({}, res.data)) {
        this.dept = []
        return
      }

      this.dept = res.data
    },
    async getPositions() {
      const res = await getPosition()
      this.position = res.data
    },
    async getUsers() {
      this.loading = true
      try {
        const res = await getAllUser(Object.assign(this.postData, this.pageData))
        this.loading = false
        this.tableData = res.data.map(item => {
          const data = {}
          item.fieldData.forEach(field => {
            const f = field?.field?.field
            data[f] = field?.valueType ? {
              value: field?.content,
              valueType: field?.valueType
            } : field?.content
          })
          return {
            ...item,
            ...data
          }
        })
        this.meta = res.meta
      } catch (e) {
        console.log('e ------>', e)
      }
    },
    handlerShow(data) {
      console.log(data)
      this.$router.push({
        path: `/personnel-files/show/${data.id}`,
        query: { tag_title: data.username + '-查看', show: true }
      })
    },
    pagination(page) {
      this.pageData.page = page.page
      this.pageData.paginate = page.limit
      this.getUsers()
    },
    onSubmit() {
      this.postData = deepClone(this.form)
      const fieldSearch = Object
        .entries(this.searchCondition)
        .map(item => {
          return {
            id: item[1].id,
            field: item[1].field,
            search: item[1].search
            // table: item[1].ofTable
          }
        })
      this.postData['field_search'] = JSON.stringify(fieldSearch)
      this.pageData.page = 1
      console.log(this.postData)
      if (this.postData.department_id) {
        // const arr = []
        // this.postData.department_id.forEach((el) => {
        //   arr.push(el[el.length - 1])
        // })
        this.postData.department_id = this.postData.department_id[this.postData.department_id.length - 1]
      }
      // if (this.postData.department_id?.length <= 0) {
      //   this.$delete(this.postData, 'department_id')
      // } else {
      //   this.postData.department_id = JSON.stringify(
      //     this.postData.department_id
      //   )
      // }
      if (this.postData.position_id?.length <= 0) {
        this.$delete(this.postData, 'position_id')
      } else {
        this.postData.position_id = JSON.stringify(this.postData.position_id)
      }
      if (this.postData.job_status?.length <= 0) {
        this.$delete(this.postData, 'job_status')
      } else {
        this.postData.job_status = JSON.stringify(this.postData.job_status)
      }
      this.getUsers()
    },
    handleCommand(command, data) {
      console.log(command, data)
      this.num = data.id
      switch (command) {
        case '1':
          this.pwdId = data.id
          this.pwdDialogVisible = true
          break
        case '2':
          // 确保调用子组件方法的时候已经渲染完成
          this.$nextTick(() => {
            this.$refs.dorm.getDormitorys()
          })
          this.dormitoryCheckDialogVisible = true
          break
        case '3':
          const jobStatus = data.job_status / 1 === 1 ? 0 : 1

          const msg = jobStatus === 1 ? '在职' : '离职'

          this.$confirm(`确定要设置为${msg}吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (jobStatus) {
              this.handleSetResignation(data.id, jobStatus)
            } else {
              this.resignationUser = data.id
              this.resignationDialogVisible = true
            }
          })
          break
      }
    },

    async handleSetResignation(userId, jobStatus) {
      this.resignationDialogBtnLoading = true
      const field = JSON.stringify({ 52: jobStatus })
      try {
        await administratorModifyFile({
          user_id: userId,
          field: field
        })
        this.onSubmit()
        this.$message.success('操作成功')
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '操作失败')
      } finally {
        this.resignationDialogBtnLoading = false
      }
    },

    pwdFinish() {
      this.pwdDialogVisible = false
    },

    getRowKey(row) {
      return row.id
    },

    handleSelectionChange(e) {
      this.currentEmployees = e.map(item => item.id)
    },

    handleExportEmployeesInfo() {
      const ids = JSON.stringify(this.currentEmployees)
      this.exportEmployeesApi(ids)
    },

    async exportEmployeesApi(ids) {
      try {
        const res = await exportEmployeeInfo({ user_id: ids })
        if (res.code === 200) {
          this.$message.success('导出成功')
          window.open(res.data.path)
          this.clearSelectionEvent()
        }
      } catch (error) {
        this.$message.error(error.message || '导出失败')
      }
    },

    clearSelectionEvent() {
      this.currentEmployees = []
      this.$refs.elTableRef.clearSelection()
    },

    formatterLaborContract(fieldList, fieldId) {
      return fieldList?.filter(f => f.field.id === fieldId)[0]
    },

    async handleResignationDialogConfirm(userId) {
      await this.handleSetResignation(userId, 0)
      this.resignationDialogVisible = false
    }

  }
}
</script>

<style lang="scss" scoped>
.documentation-container {
  padding: 0 20px 20px 20px;
  //.el-form-item{
  //  margin-bottom: 0px;
  //}

  .document-btn {
    flex-shrink: 0;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    padding: 0 16px;
    margin: 16px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
  .employee__header {
    padding: 0 0 20px 0;
  }
}

::v-deep(.el-card) {
  .el-card__body {
    padding: 20px 20px 0 20px;
  }
}
</style>
